using FluentValidation;
using MediatR;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Events;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Queries.Interfaces;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;


public record GetQuestionQuery(int Id) : IQuery<Result<QuestionDto>>;


public class GetQuestionQueryValidator : AbstractValidator<GetQuestionQuery>
{
    public GetQuestionQueryValidator()
    {
        RuleFor(command=> command. Id)
            .GreaterThan(0);
    }
}
public class GetQuestionQueryHandler(IDaraQueryService dataQueryService,IPublisher publisher) :IQueryHandler<GetQuestionQuery, Result<QuestionDto>>
{
    public async Task<Result<QuestionDto>> Handle(GetQuestionQuery request, CancellationToken cancellationToken)
    {
        var queryable = dataQueryService.Questions
            .Where(q => q.Id == request.Id)
            .Select(q => new QuestionDto
            {
                Id = q.Id,
                Title = q.Title,
                Description = q.Description,
                AnswerCount = q.Answers.Count,
                FollowerCount = q.FollowCount,
                ViewCount = q.ViewCount
            });
        
        var questionDto = await dataQueryService.FirstOrDefaultAsync(queryable);

        if (questionDto == null) return Result.NotFound("问题不存在");
        
        await publisher.Publish(new QuestionViewedEvent(questionDto.Id), cancellationToken);

        return Result.Success(questionDto);

    }
}